import { DEV } from "@follow/shared/constants"

import { getClientId, getSessionId } from "~/lib/client-session"

import { followClient } from "./api-client"

class Analytics4 {
  private clientID: string
  private sessionID: string
  private userID: string | null = null
  private userProperties: Record<string, { value: unknown }> | null = null

  constructor(clientID: string = getClientId(), sessionID = getSessionId()) {
    this.clientID = clientID
    this.sessionID = sessionID
  }

  async setUserId(id: string) {
    this.userID = id
  }

  async setUserProperties(upValue?: Record<string, unknown>) {
    const userProperties = Object.entries(upValue || {}).reduce((acc, [key, value]) => {
      acc[key] = {
        value,
      }
      return acc
    }, {})
    this.userProperties = userProperties
  }

  async logEvent(eventName: string, params?: Record<string, unknown>): Promise<any> {
    delete params?.__code
    delete params?.__eventName

    const payload = {
      client_id: this.clientID,
      user_id: this.userID,
      events: [
        {
          name: eventName,
          params: {
            session_id: this.sessionID,
            engagement_time_msec: 1000,
            ...params,
          },
        },
      ],
      user_properties: this.userProperties,
    }

    // 在开发环境下，只打印日志而不发送实际请求
    if (DEV) {
      // eslint-disable-next-line no-console
      console.log("[Analytics] Would send event:", eventName, payload)
      return { success: true, message: "Development mode - no actual request sent" }
    }

    // 在生产环境下，尝试发送请求但添加错误处理
    try {
      if (followClient.api.data && followClient.api.data.sendAnalytics) {
        return await followClient.api.data.sendAnalytics({
          ...payload,
        })
      } else {
        console.warn("[Analytics] sendAnalytics API not available")
        return { success: false, message: "API not available" }
      }
    } catch (error) {
      console.warn(`[Analytics] Failed to send event "${eventName}":`, error)
      return { success: false, error: error instanceof Error ? error.message : String(error) }
    }
  }
}

export const ga4 = new Analytics4()
